"use strict"

var http = require('http');

var httpServer = http.createServer(processRequest);
var port = 8000;

httpServer.listen(port, function() {
  console.log(`server is running at port: ${port}`);
  console.log(`url: http://localhost:${port}`);
});

function processRequest(request, response) {
  var pathName = request.url;

  if (pathName === "/") {
    response.writeHead(200, {'content-type': 'text/html'});
    response.end('<h1>Simple http server is running.</h1>');
    return;
  }

  var fullUrl = `http://localhost:${port}${pathName}`;
  console.log(fullUrl);

  var url = new URL(fullUrl);
  console.log(url.pathname);

  var pureName = url.pathname.toLowerCase();

  if (pureName === '/jsonp-test') {
    doJsonp(url, request, response);
    return;
  }
  else if (pureName === '/jsonp-validateuser') {
    doValidateUser(url, request, response);
    return;
  }

  response.writeHead(404, {'content-type': 'application/json'});
  response.end('{"success": false, "statustext": "unknow service."}');
}

function doJsonp(url, request, response){
  response.writeHead(200, {'content-type': 'text/javascript; charset=UTF-8'});

  var data = {};
  url.searchParams.forEach((value, key, parent) => {
    data[key] = value;
  });

  var callback = url.searchParams.get('callback');
  if (callback) {
    delete data.callback;
    var json = JSON.stringify(data);
    response.end(`${callback}(${json})`);
  }else{
    var json = JSON.stringify(data);
    response.end(`handle(${json})`);
  }
}

function doValidateUser(url, request, response) {
  response.writeHead(200, {'content-type': 'text/javascript; charset=UTF-8'});

  var data = {"success": false, "message": "用户名不存在！"};
  var user = url.searchParams.get('user');
  if(user){
    data['user'] = user;
  }
  var json = JSON.stringify(data);

  var callback = url.searchParams.get('callback');
  if (callback) {
    response.end(`${callback}(${json})`);
  }else{
    response.end(`handle(${json})`);
  }
}